package cn.wolfcode.car.business.service.impl;



import cn.wolfcode.car.business.domain.BpmnInfo;

import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQueryObject;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;

import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.web.AjaxResult;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramCanvas;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.zip.ZipInputStream;


@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
   


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<BpmnInfo> bpmnInfos = bpmnInfoMapper.selectForList(qo);
        return new TablePageInfo<BpmnInfo>(bpmnInfos);
    }
    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }



    @Override//部署文件
    public String upload(String bpmnPath,String bpmnType,String info) {
        //路径拼接进来可能会有大写,统一转成小写,为了比较好比较
        String lowerCase = bpmnPath.toLowerCase();
        //判断路径不为空
        if (bpmnPath != null) {
            try {
                //创建一个输入流,后面通过输入流来创建部署对象
                FileInputStream stream = new FileInputStream(new File(SystemConfig.getUploadPath(), bpmnPath));
                //创建一个空的部署对象来接收
                Deployment deploy = null;
                //部署对象
                if ("zip".endsWith(lowerCase)){
                     deploy = repositoryService.createDeployment()
                            //如果是压缩包类型zip,就用对应的压缩包api导入
                            .addZipInputStream(new ZipInputStream(stream))
                            .deploy();
                }else {
                   deploy= repositoryService.createDeployment()
                           .addInputStream(bpmnPath,stream)
                           .deploy();
                }
                //判断deploy是不是为空
                if (deploy == null) {
                    throw new BusinessException("部署失败");
                }
                //获取deployee中的数据封装到bpmb对象中去
                BpmnInfo bpmnInfo = new BpmnInfo();

                bpmnInfo.setBpmnType(bpmnType);
                bpmnInfo.setDeploymentId(deploy.getId());
                bpmnInfo.setDeployTime(deploy.getDeploymentTime());
                bpmnInfo.setInfo(info);
                //获取流程定义对象
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                        //部署对象id
                        .deploymentId(deploy.getId())
                        //最后一个版本
                        .latestVersion()
                        //获取一个对象
                        .singleResult();

                bpmnInfo.setActProcessId(processDefinition.getId());
                bpmnInfo.setActProcessKey(processDefinition.getKey());
                //部署流程名字
                bpmnInfo.setBpmnName(processDefinition.getName());

                //插入保存bpmnInfo对象
                bpmnInfoMapper.insert(bpmnInfo);

                //返回
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


        }else {
            throw new BusinessException("错误参数");
        }
        return null;
    }

    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId).latestVersion().singleResult();
        if("xml".equalsIgnoreCase(type)){
            return repositoryService.getResourceAsStream(deploymentId, definition.getResourceName());
        }else if("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
            return inputStream;
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String car_package) {
      return bpmnInfoMapper.selectByPrimaryType(car_package);

    }


    @Override//保存
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }




    @Override//删除
    public void deleteBatch(Long ids) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(ids);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion()
                .singleResult();



        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file.exists()){
            file.delete();
        }
        //删除对应部署对象
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        //删除上传的部署文件
        //删除bpmb文件
        bpmnInfoMapper.deleteByPrimaryKey(ids);
    }
}
